package net.zigin.nhi.waste.view.alarm;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.bean.AlarmBoxBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.JsonParser;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.widget.BoxAlarmDialog;
import net.zigin.nhi.waste.view.widget.DialogManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 医废箱出库超重预警界面
 */
public class AlarmBoxActivity extends AppCompatActivity {

    private ImageView mAlarmImg;
    private TextView mAlarmType;
    private TextView mAlarmWeight;
    private TextView mBoxNum;
    private TextView mWasteType;
    private TextView mWasteTemp;
    private TextView mCollectWeight;
    private TextView mCollectTime;
    private TextView mInWeight;
    private TextView mInTime;
    private TextView mOutWeight;
    private TextView mOutTime;
    private TextView mCollector;
    private TextView mHandover;
    private RelativeLayout mDetailLayout;
    private EditText mRemark;
    private Button mBtnSpeech;
    private Button mCommit;
    private RelativeLayout mRemarkLayout;
    private RelativeLayout mModifyLayout;
    private TextView mModifyRemark;
    private TextView mModifyUser;
    private TextView mModifyTime;

    private List<AlarmBoxBean> baseList = new ArrayList<>();

    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_box_detail);

        initView();
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mAlarmImg = findViewById(R.id.alarm_img);
        mAlarmType = findViewById(R.id.alarm_type);
        mAlarmWeight = findViewById(R.id.alarm_weight);
        mBoxNum = findViewById(R.id.box_num);
        mWasteType = findViewById(R.id.waste_type);
        mWasteTemp = findViewById(R.id.waste_temp);
        mCollectWeight = findViewById(R.id.collect_weight);
        mCollectTime = findViewById(R.id.collect_time);
        mInWeight = findViewById(R.id.in_weight);
        mInTime = findViewById(R.id.in_time);
        mOutWeight = findViewById(R.id.out_weight);
        mOutTime = findViewById(R.id.out_time);
        mCollector = findViewById(R.id.collector);
        mHandover = findViewById(R.id.handover);
        mDetailLayout = findViewById(R.id.detail_layout);
        mRemark = findViewById(R.id.remark);
        mBtnSpeech = findViewById(R.id.btnSpeech);
        mCommit = findViewById(R.id.commit);
        mRemarkLayout = findViewById(R.id.remark_layout);
        mModifyLayout = findViewById(R.id.modify_layout);
        mModifyRemark = findViewById(R.id.modify_remark);
        mModifyUser = findViewById(R.id.modifyUser);
        mModifyTime = findViewById(R.id.modify_time);
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = code -> {
        Log.d("语音听写", "SpeechRecognizer init() code = " + code);
        if (code != ErrorCode.SUCCESS) {
            Toast.makeText(AlarmBoxActivity.this, "语音听写初始化失败", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d("语音听写", "recognizer result：" + results.getResultString());

            String text = JsonParser.parseIatResult(results.getResultString());
            mRemark.append(text);
            mRemark.setSelection(mRemark.length());
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            Toast.makeText(AlarmBoxActivity.this, error.getPlainDescription(true), Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 参数设置
     */
    public void setParam() {
        // 清空参数
//        mIat.setParameter(SpeechConstant.PARAMS, null);
        String lag = "en_us";
        // 设置引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        mIat.setParameter(SpeechConstant.ACCENT, null);
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, lag);
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                getExternalFilesDir("msc").getAbsolutePath() + "/iat.wav");
    }

    /**
     * 开启语音识别对话框，将说的话转成文字
     */
    private void speechToText() {
        setParam();
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        TextView txt = mIatDialog.getWindow().getDecorView().findViewWithTag("textlink");
        txt.setText("");
        txt.getPaint().setFlags(Paint.SUBPIXEL_TEXT_FLAG);//取消下划线
        txt.setEnabled(false);
        Toast.makeText(AlarmBoxActivity.this, "请开始说话...", Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("CheckResult")
    private void initData() {
        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String objectCode = intent.getStringExtra("objectCode");
        String alarm_type = intent.getStringExtra("alarm_type");
        String objectId = intent.getStringExtra("objectId");

        String modifyStatus = intent.getStringExtra("modifyStatus");
        String remark = intent.getStringExtra("modifyRemark");
        String modifyTime = intent.getStringExtra("modifyTime");
        String modifyUser = intent.getStringExtra("modifyUser");

        if ("done".equals(modifyStatus)) {
            mModifyLayout.setVisibility(View.VISIBLE);
            mRemarkLayout.setVisibility(View.GONE);
            mModifyRemark.setText(remark);
            mModifyTime.setText(modifyTime);
            mModifyUser.setText(modifyUser);
        } else {
            mModifyLayout.setVisibility(View.GONE);
            mRemarkLayout.setVisibility(View.VISIBLE);
        }

        mBoxNum.setText(objectCode);

        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .warnInfoByBoxRecordId(Paper.book().read(Constants.TOKEN), objectId);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @SuppressLint({"SetTextI18n", "DefaultLocale"})
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("告警详情", data);
                    baseList.clear();
                    JSONObject object = JSON.parseObject(data);
                    JSONObject wasteBoxRecord = object.getJSONObject("wasteBoxRecord");
                    String collectWeight = object.getString("collectWeight");
                    String inWeight = wasteBoxRecord.getString("inWeight");
                    String outWeight = wasteBoxRecord.getString("outWeight");
                    if (StringUtil.isNotEmpty(collectWeight)) {
                        double col = Double.parseDouble(collectWeight);
                        mCollectWeight.setText(String.format("%.2f", col) + "kg");
                    }
                    if (StringUtil.isNotEmpty(inWeight)) {
                        double in = Double.parseDouble(inWeight);
                        mInWeight.setText(String.format("%.2f", in) + "kg");
                    }
                    if (StringUtil.isNotEmpty(outWeight)) {
                        double out = Double.parseDouble(outWeight);
                        mOutWeight.setText(String.format("%.2f", out) + "kg");
                    }
                    mInTime.setText(wasteBoxRecord.getString("inTime"));
                    mOutTime.setText(wasteBoxRecord.getString("outTime"));

                    switch (alarm_type) {
                        case "in_depot_weight_red":
                            mAlarmType.setText("超重入库红色预警");
                            mAlarmType.setTextColor(Color.parseColor("#F4664A"));
                            mAlarmImg.setImageResource(R.drawable.red_weight);
                            mInWeight.setTextColor(Color.parseColor("#F4664A"));
                            mOutWeight.setTextColor(Color.parseColor("#333333"));
                            double weight = Double.parseDouble(mInWeight.getText().toString().replace("kg", "")) - Double.parseDouble(mCollectWeight.getText().toString().replace("kg", ""));
                            mAlarmWeight.setText(String.format("%.2f", Math.abs(weight)));
                            break;
                        case "in_depot_weight_yellow":
                            mAlarmType.setText("超重入库黄色预警");
                            mAlarmType.setTextColor(Color.parseColor("#FFAA00"));
                            mAlarmImg.setImageResource(R.drawable.yellow_weight);
                            mInWeight.setTextColor(Color.parseColor("#FFAA00"));
                            mOutWeight.setTextColor(Color.parseColor("#333333"));
                            double weight2 = Double.parseDouble(mInWeight.getText().toString().replace("kg", "")) - Double.parseDouble(mCollectWeight.getText().toString().replace("kg", ""));
                            mAlarmWeight.setText(String.format("%.2f", Math.abs(weight2)));
                            break;
                        case "out_depot_weight_red":
                            mAlarmType.setText("超重出库红色预警");
                            mAlarmType.setTextColor(Color.parseColor("#F4664A"));
                            mAlarmImg.setImageResource(R.drawable.red_weight);
                            mOutWeight.setTextColor(Color.parseColor("#F4664A"));
                            mInWeight.setTextColor(Color.parseColor("#333333"));
                            double weight3 = Double.parseDouble(mOutWeight.getText().toString().replace("kg", "")) - Double.parseDouble(mCollectWeight.getText().toString().replace("kg", ""));
                            mAlarmWeight.setText(String.format("%.2f", Math.abs(weight3)));
                            break;
                        case "out_depot_weight_yellow":
                            mAlarmType.setText("超重出库黄色预警");
                            mAlarmType.setTextColor(Color.parseColor("#FFAA00"));
                            mAlarmImg.setImageResource(R.drawable.yellow_weight);
                            mOutWeight.setTextColor(Color.parseColor("#FFAA00"));
                            mInWeight.setTextColor(Color.parseColor("#333333"));
                            double weight4 = Double.parseDouble(mOutWeight.getText().toString().replace("kg", "")) - Double.parseDouble(mCollectWeight.getText().toString().replace("kg", ""));
                            mAlarmWeight.setText(String.format("%.2f", Math.abs(weight4)));
                            break;
                    }

                    baseList = JSONArray.parseArray(object.getString("wasteBases"), AlarmBoxBean.class);
                    if (baseList != null && baseList.size() > 0) {
                        mCollectTime.setText(baseList.get(0).getCreateTime());
                        mWasteTemp.setText(baseList.get(0).getHospitalPlaceName());
                        mCollector.setText(baseList.get(0).getCollectUserStaffName());
                        mHandover.setText(baseList.get(0).getHandUserStaffName());
                        mWasteType.setText(baseList.get(0).getWasteClassifyName());
                    }
                }
            }
        });

        mDetailLayout.setOnClickListener(v -> {
            BoxAlarmDialog dialog = new BoxAlarmDialog(this, AlarmBoxActivity.this, baseList);
            dialog.show();
        });

        mBtnSpeech.setOnClickListener(v -> {
            RxPermissions permissions = new RxPermissions(this);
            permissions.request(Manifest.permission.RECORD_AUDIO)
                    .subscribe(granted -> {
                        if (!granted) { //申请失败
                            Toast.makeText(this, "权限未开启, 将无法识别语音！", Toast.LENGTH_SHORT).show();
                        } else {
                            speechToText();
                        }
                    });
        });

        mCommit.setOnClickListener(v -> {
            if (StringUtil.isNotEmpty(mRemark.getText().toString())) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("remark", mRemark.getText().toString());
                Observable<BaseResponse<String>> observable1 = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .dealWith(Paper.book().read(Constants.TOKEN), map);
                DialogManager.getInstance().showLoading(AlarmBoxActivity.this);
                HttpRetrofitClient.execute(observable1, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        Toast.makeText(AlarmBoxActivity.this, "处理完成！", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            } else {
                Toast.makeText(AlarmBoxActivity.this, "请填写处理意见！", Toast.LENGTH_SHORT).show();
            }
        });
    }
}